package com.swing.sky.system.framework.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.swing.sky.common.web.SkyResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public static final String JSON = "JSON";
    @Value("${other.responseType}")
    private String responseType;

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        if (JSON.equalsIgnoreCase(responseType)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(OBJECT_MAPPER.writeValueAsString(SkyResponse.success("\u767B\u5F55\u6210\u529F")));
        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}